package org.example.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.example.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author liyishan
 * @date 2023/7/18 18:38
 * @apiNote
 */
@RestController
@RequestMapping("testRibbon")
public class TestController {
    @Autowired
    private TestService testService;


    @Autowired
    private RestTemplate restTemplate;
    @Value("${service-url.ddd-demo}")
    private String dddServiceUrl;


    @HystrixCommand(fallbackMethod = "getDefaultDemo")
    @GetMapping("ribbonDemo")
    public String demo(){
        return restTemplate.getForObject(dddServiceUrl+"/test/demo",String.class);
    }

    @HystrixCommand(fallbackMethod = "getDefaultDemo")
    @GetMapping("ribbonDemo1")
    public String demo1(String name){
        return restTemplate.getForObject(dddServiceUrl+"/test/demo1?name={1}",String.class,name);
    }

    public String getDefaultDemo(){
        return "wait";
    }

    public String getDefaultDemo(String name){
        return name+"wait";
    }


    @GetMapping("test")
    public String test(String name){
        String result = testService.test(name);
        result += testService.test(name);
        result += testService.test(name);
        return result;
    }

    /**
     *      过滤器里加 Hystrix 的上下文  HystrixRequestContext context = HystrixRequestContext.initializeContext();
     *      才能使用 Hystrix 的缓存功能
     * @param name
     * @return
     */
    @GetMapping("testMore")
    public String testMore(String name){
        String result = testService.getFutrue(name+"1");
        result += testService.getFutrue(name+"2");
        result += testService.getFutrue(name+"3");
        return result;
    }

}
